class WebSocketManager {
  private socketTask: WechatMiniprogram.SocketTask | null = null;
  public isOpened: boolean = false;
  private reconnectTimer: number | null = null;
  private reconnectCount: number = 0;
  private maxReconnectCount: number = 5;
  private messageCallback: ((data: any) => void) | null = null;

  // 建立连接
  connect(token: string): Promise<void> {
    return new Promise((resolve, reject) => {
      // 检查是否已经连接
      if (this.isOpened) {
        console.log('WebSocket 已经连接，无需重新连接');
        resolve();
        return;
      }

      // 如果存在旧的 socketTask，先关闭
      if (this.socketTask) {
        this.socketTask.close({});
      }

      // 使用token作为查询参数
      this.socketTask = wx.connectSocket({
        // url: `ws://192.168.2.11:8080/ws/chat?token=${token}`,
        url: `wss://tour.dwtcy.com.cn/ws/chat?token=${token}`,
        header: {
          'content-type': 'application/json'
        }
      });

      this.socketTask.onOpen(() => {
        console.log('WebSocket连接成功');
        this.isOpened = true;
        this.reconnectCount = 0;
        resolve();
      });

      this.socketTask.onError((err) => {
        console.error('WebSocket连接错误', err);
        this.isOpened = false;
        reject(err);
      });

      this.socketTask.onClose(() => {
        console.log('WebSocket连接已关闭');
        this.isOpened = false;
        // 尝试重连
        // this.reconnect(token);
      });

      this.socketTask.onMessage((res) => {
        try {
          const data = JSON.parse(res.data as string);
          if (this.messageCallback) {
            this.messageCallback(data);
          }
        } catch (error) {
          console.error('解析消息失败', error);
        }
      });
    });
  }

  // 设置消息回调
  onMessage(callback: (data: any) => void): void {
    this.messageCallback = callback;
  }

  // 发送消息
  sendMessage(to: string, message: string, role: string = 'WXUSER'): void {
    if (!this.isOpened || !this.socketTask) {
      console.error('WebSocket未连接');
      return;
    }
    const msgData = {
      to: to,
      message: message,
      role: role
    };

    this.socketTask.send({
      data: JSON.stringify(msgData),
      success: () => {
        console.log('消息发送成功');
      },
      fail: (err) => {
        console.error('消息发送失败', err);
      }
    });
  }

  // 关闭连接
  close(): void {
    // 检查是否已经存在 socketTask
    if (this.socketTask) {
      try {
        this.socketTask.close({});
      } catch (error) {
        console.warn('关闭WebSocket连接失败:', error);
      }
    }
    
    // 清理定时器
    if (this.reconnectTimer) {
      clearTimeout(this.reconnectTimer);
    }
    
    // 重置状态
    this.isOpened = false;
    this.messageCallback = null;
    this.socketTask = null; // 明确设置为null
  }

  // 重连机制
  private reconnect(token: string): void {
    if (this.reconnectCount < this.maxReconnectCount) {
      this.reconnectTimer = setTimeout(() => {
        this.reconnectCount++;
        console.log(`尝试重连第${this.reconnectCount}次`);
        this.connect(token);
      }, 3000);
    } else {
      console.error('达到最大重连次数,停止重连');
    }
  }
}

export default new WebSocketManager();